Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number

12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1


In [3]:
class Solution(object):
    def happy_jude(self, n):
        s = str(n)
        sum = 0
        for c in s:
            sum += (ord(c)-ord('0'))**2
        return sum
    
    def isHappy(self, n):
        """
        首先计算每个数字happy值,
        仔细研究就会发现其实每个字都有自身的循环周期
        所以这道题的关键就是找到这个循环周期,只要判断
        1在不在这个周期里面就可以了
        :type n: int
        :rtype: bool
        """
        a_set = set([n])
        con = self.happy_jude(n)
        while con not in a_set:
            a_set.add(con)
            con = self.happy_jude(con)
        if 1 in a_set:
            return True
        else:
            return False

In [4]:
Solution().isHappy(19)


Out[4]:
True

In [ ]:
def happy(n):
    a_set = set([n])
    con = happy_jude(n)
    while con not in a_set:
        a_set.add(con)
        con = happy_jude(con)
    if 1 in a_set:
        return True
    else:
        return False

In [ ]:
for i in range (1, 100):
    print("num", i)
    print(happy(i))
    print("num end")

In [ ]: